#pragma once
#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <cstring>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>
#include <unistd.h>
#include "Log.hpp"
using namespace std;

#define CONVERT(addr) ((struct sockaddr*)&addr)

class INETADDR
{
public:
    INETADDR() = default;
    // 网络序列转主机序列
    INETADDR(struct sockaddr_in &addr)
    {
        SetAddr(addr);
    }
    // 主机序列转网络序列
    INETADDR(const string &ip, uint16_t port)
        : _ip(ip), _port(port)
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        int n = inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
        if (n != 1)
        {
            LOG(LogLevel::FATAL) << "inet_pton erro";
            exit(1);
        }
        _addr.sin_port = htons(_port);
    }
    // 主机序列转网络序列
    INETADDR(uint16_t port)
        : _ip(), _port(port)
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_addr.s_addr = INADDR_ANY;
        _addr.sin_port = htons(_port);
    }
    void SetAddr(struct sockaddr_in& addr)
    {
        _addr = addr;
        _port = ntohs(_addr.sin_port);
        char buffer[64] = {0};
        const char *result = inet_ntop(AF_INET, &addr.sin_addr, buffer, sizeof(addr));
        if (!result)
        {
            LOG(LogLevel::FATAL) << "inet_ntop erro";
            exit(1);
        }
        _ip = buffer;
    }
    uint16_t Port()
    {
        return _port;
    }
    string IP()
    {
        return _ip;
    }
    string StringAddr()
    {
        return _ip + ":" + to_string(_port);
    }
    const struct sockaddr_in &NetAddr()
    {
        return _addr;
    }
    const struct sockaddr *NetAddrPtr()
    {
        return CONVERT(_addr);
    }
    socklen_t NetAddrLen()
    {
        return sizeof(_addr);
    }
    bool operator==(INETADDR &addr)
    {
        return addr._ip == _ip && addr._port == _port;
    }

    ~INETADDR()
    {
    }

private:
    struct sockaddr_in _addr;
    uint16_t _port;
    string _ip;
};